package com.ruiysoft.crm.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ruiysoft.crm.mapper.SysUserMapper;
import com.ruiysoft.crm.model.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


//@WebFilter(urlPatterns = "/*", filterName = "authFilter")
public class LangFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Autowired
    SysUserMapper userMapper;



    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

      /*  ChangeRequestWrapper changeRequestWrapper = new ChangeRequestWrapper((HttpServletRequest) servletRequest);
        Map<String, String[]> parameterMap = new HashMap<>(changeRequestWrapper.getParameterMap());
        String url = ((HttpServletRequest) servletRequest).getRequestURI();
        String userId = ((HttpServletRequest) servletRequest).getHeader("userId");
        System.out.println(url + ", " + userId);

        if(userId != null) {
            UserVO userVO = userMapper.selectUserVoById(Integer.parseInt(userId));
            parameterMap.putAll(getObjectToMap(userVO));
          //  parameterMap = getObjectToMap(userVO);
            parameterMap.remove("roleList");
            changeRequestWrapper.setParameterMap(parameterMap);
            filterChain.doFilter(changeRequestWrapper, servletResponse);

        } else*/
            filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

    public static Map<String, String[]> getObjectToMap(Object obj)  {
        Map<String, String[]> map = new LinkedHashMap<String, String[]>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (value == null){
                value = "";
            }
            map.put(fieldName, new String[]{value+""});
        }
        return map;
    }
}